<?php

namespace App\Process;

use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\Component\Pool\PoolManager;

abstract class ProcessBase
{
    protected $db;

    /**
     * 数据初始化
     * ProcessBase constructor.
     * @param array $runData
     * @throws \Throwable
     */
    public function __construct(array $runData = [])
    {
        $this->db = PoolManager::getInstance()->getPool(MysqlPool::class)->getObj();
        $this->start($runData);
    }

    /**
     * 获取数据联接对象
     * @return MysqlObject
     */
    public function getDb(): MysqlObject
    {
        return $this->db;
    }

    /**
     * 开始执行
     * @return mixed
     */
    abstract function start();

    /**
     * 获取执行结果
     * @return string
     */
    public function getServerResult()
    {
        if (is_bool($this->result)) {
            return $this->result ? '??' : '??';
        }
        return $this->result;
    }

    /**
     * 添加条件操作
     * @param $where
     * @return $this
     */
    public function addWhereMap($where)
    {
        if (is_array($where)) {
            foreach ($where as $k => $v) {
                $kArr = explode('|', $k);
                $this->getDb()->where($kArr[0], $v, isset($kArr[1]) ? $kArr[1] : '=');
            }
        } else {
            $this->getDb()->where($where[0] . $where[1], '=');
        }
        return $this;
    }


    /**
     *销毁联接对象
     * @throws \Throwable
     */
    public function __destruct()
    {
        PoolManager::getInstance()->getPool(MysqlPool::class)->recycleObj($this->db);
    }


}